package com.example.demo.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

 public class DistributedLockUtil {
     private static final String LOCK_PREFIX = "distributed_lock:";
     private static final long LOCK_EXPIRE_TIME = 120; // 锁过期时间，单位：秒

     private StringRedisTemplate stringRedisTemplate;

     public DistributedLockUtil(StringRedisTemplate stringRedisTemplate) {
         this.stringRedisTemplate = stringRedisTemplate;
     }

     public boolean tryLock(String lockKey, Long expireTime) {
         String lockFullKey = LOCK_PREFIX + lockKey;
         // 使用SETNX命令尝试获取锁
         Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockFullKey, "locked");
         if (result!= null && result) {
             // 设置锁的过期时间
             stringRedisTemplate.expire(lockFullKey, LOCK_EXPIRE_TIME, TimeUnit.SECONDS);
             return true;
         }
         return false;
     }

     public void unlock(String lockKey) {
         String lockFullKey = LOCK_PREFIX + lockKey;
         String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
         RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
         Long result = stringRedisTemplate.execute(redisScript, Collections.singletonList(lockFullKey), "locked");
     }
 }